package org.lemon.db.store;

import org.lemon.common.DBException;
import org.lemon.common.util.IOUtils;
import org.lemon.db.store.fs.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;

/**
 * 这个类是随机文件的一个抽象
 */
public class FileStore {
    /**
     * The file name.
     */
    protected String name;
    private final String mode;
    private FileChannel fileChannel;

    /**
     * Create a new file using the given settings.
     * @param name
     * @param mode
     */
    protected FileStore(String name, String mode) {
        this.name = name;
        File file = new File(name);
        boolean exists = file.exists();
        if (exists && !file.canWrite()) {
            mode = "r";
        }
        try {
            fileChannel = FileChannel.open(Paths.get(name),FileUtils.modeToOptions(mode));
        } catch (IOException e) {
            throw DBException.convertIOException(
                e, "name: " + name + " mode: " + mode);
        }
        this.mode = mode;
    }


    protected final void readFully(ByteBuffer dst, long pos, int len) {
        IOUtils.readFully(fileChannel,pos,dst);

        //readCount.incrementAndGet();
        //readBytes.addAndGet(len);
    }

    protected final void writeFully(ByteBuffer src,long pos ,int len){
       IOUtils.writeFully(fileChannel,pos,src);
    }


    /**
     * Open a non encrypted file store with the given settings.
     *
     * @param name the file name
     * @param mode the access mode (r, rw, rws, rwd)
     * @return the created object
     */
    public static FileStore open( String name, String mode) {
        return new FileStore(name,mode);
    }
}
